#pragma once

#include <iostream>
#include <pthread.h>
#include <signal.h>
#include <thread>
#include <chrono>
#include "Log.hpp"
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"
#define PORT 8080

class HttpServer
{
private:
    int port;
    bool stop;

public:
    HttpServer(int _port = PORT) : port(_port), stop(false)
    {
    }
    void InitServer()
    {
        // 信号SIGPIPE需要进行忽略，如果不忽略，在写入时候，可能直接崩溃server
        signal(SIGPIPE, SIG_IGN);
    }
    void Loop()
    {
        TcpServer *tsvr = TcpServer::get_instance(port);
        ILOG("Loop begin");
        while (!stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(tsvr->sock(), (struct sockaddr *)&peer, &len);
            if (sock < 0)
            {
                continue;
            }
            ILOG("Get a new link: %d", sock);
            Task t(sock);
            ThreadPool::getinstance()->PushTask(t);
        }
    }
    ~HttpServer()
    {
    }
};
